package com.ermao.mymes.handler.pending;

import com.ermao.mymes.common.domain.TaskInfo;
import com.ermao.mymes.handler.handler.HandlerHolder;
import com.ermao.mymes.handler.service.deduplication.DeduplicationRuleService;
import com.ermao.mymes.handler.service.discard.DiscardMessageService;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author Ermao
 * Date: 2022/5/8 14:38
 */
@Data
@Accessors(chain = true)
@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Task implements Runnable {
	@Autowired
	private HandlerHolder handlerHolder;

	@Autowired
	private DeduplicationRuleService deduplicationRuleService;

	@Autowired
	private DiscardMessageService discardMessageService;

	private TaskInfo taskInfo;

	@Override
	public void run() {

		// 0. TODO 丢弃消息
		if (discardMessageService.isDiscard(taskInfo)) {
			log.error("丢弃了任务：{}", taskInfo);
			return;
		}

		// 1. 通用去重
		deduplicationRuleService.duplication(taskInfo);

		// 2. 真正发送消息 TODO taskInfo 中的 receiver 为空时调用腾讯云脚本发送消息会抛出异常
		handlerHolder.route(taskInfo.getSendChannel())	// route 方法获取到对应的 handler
				.doHandler(taskInfo);

	}
}
